package com.zweirm.lagee_quizing.controller;

import com.zweirm.lagee_quizing.domain.*;
import com.zweirm.lagee_quizing.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ResultController {
    @Autowired
    private QuizService quizService;

    @Autowired
    private ClazzService clazzService;

    @Autowired
    private ResultService resultService;

    @Autowired
    private StudentUserService studentUserService;

    @Autowired
    private PaperService paperService;

    @RequestMapping("/quizResult/{quizId}")
    public String showQuizResult(@PathVariable Long quizId, Model model) {
        // 获取考试信息
        Quiz quiz = quizService.findQuizById(quizId);
        model.addAttribute("quiz_title", quiz.getTitle());
        model.addAttribute("quiz_type", quiz.getType());

        // 获取试卷信息
        Paper paper = paperService.findPaperById(quiz.getPaper().getId());
        model.addAttribute("paper_name", paper.getName());
        model.addAttribute("paper_description", paper.getDescription());

        // 获取考试对应的班级
        List<Clazz> clazzes = clazzService.findByQuiz(quiz);
        model.addAttribute("clazzes", clazzes);

        // 获取每个班所有学生
        for (int i = 0; i < clazzes.size(); i++) {
            List<StudentUser> studentUsers = studentUserService.findByClazz(clazzes.get(i));
            List<Result> results = new ArrayList<>();
            for (StudentUser studentUser : studentUsers) {
                // 通过学生和试卷获取成绩
                Result result = resultService.findByQuizAndStudentUser(quiz, studentUser);
                if (result == null) {
                    Result tempResult = new Result();
                    tempResult.setStudentUser(studentUser);
                    tempResult.setPassRate("0.00");
                    results.add(tempResult);
                } else {
                    results.add(result);
                }
            }

            // 将数据传给前台
            model.addAttribute("clazz" + i + "results", results);
            model.addAttribute("clazz" + i + "students", studentUsers);
        }
        return "/result_details";
    }
}
